<template>
  <div>
    <HETTable
      ref="whitelistTable"
      :pageSize="whitelistTotal"
      :tableFields="whitelistTableFields"
      :tableData="whitelistTableData"
      :enableSearch="false"
      :tableCheckbox="false"
      :operationCol="treeStore.isShowStrategyDetail ? [] : operationCol"
      :headerOperation="treeStore.isShowStrategyDetail ? [] : headerOperation"
      :handleSelectionChange="handleSelectionChange"
      :total="whitelistTotal"
      @getTableData="getWhitelistTableData"
    >
    </HETTable>
    <el-dialog
      v-model="dialogFormVisible"
      title="新建路径"
      width="650"
      :center="true"
      :close-on-click-modal="false"
    >
      <el-form ref="whitelistForm" :model="form" class="px-10" :rules="rules">
        <el-form-item label="路径" prop="policyName">
          <el-input class="input-width" v-model="form.policyName" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="queryWhitelistForm"> 确认 </el-button>
          <el-button @click="dialogFormVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <DirectoryDialog
      v-if="!whitelistDialog"
      ref="whitelistDirRef"
      :rootDirFlag="rootDirFlag"
      :dirFlag="dirFlag"
      :os="treeStore.osType"
      @handleDialogButton="handleDialogButton"
    ></DirectoryDialog>
    <el-dialog
      v-if="whitelistDialog"
      v-model="whitelistDialog"
      title="策略详情"
      width="900"
      :center="true"
      :close-on-click-modal="false"
    >
      <ProgramWhitelist
        :rowData="whitelistRowData"
        :dialogShow="
          () => {
            whitelistDialog = false;
          }
        "
      ></ProgramWhitelist>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, toRaw, markRaw } from "vue";
import HETTable from "~/components/common/HETTable.vue";
import { ElMessage } from "element-plus";
import {
  req_getWhitelistPolicylist,
  req_addWhitelistPolicylist,
  req_setWhitelistPolicylist,
  req_setWhitelistDeploy,
  req_setWhitelistUndeploy,
  req_deleteWhitelistPolicylist,
  req_exportWhitelist,
  req_importWhitelist,
  req_KillList,
  req_KillAdd,
  req_KillDelete,
  req_SyncAdd,
  req_KillEdit,
} from "~/utils/axios/programWhitelist.js";
import { useTreeStore } from "~/utils/pinia/tree.js";
import { useUserStore } from "~/utils/pinia/user.js";
import { Refresh, Delete, Edit, Plus, Download, Upload } from "@element-plus/icons-vue";
import DirectoryDialog from "~/components/common/DirectoryDialog.vue";
import ProgramWhitelist from "./ProgramWhitelist.vue";
import { eventBus } from "~/utils/common/eventBus.js";
eventBus.on("getStrategyDetail", (detail) => {
  whitelistTableData.value = detail.data;
  whitelistTotal.value = detail.data.length;
});
const successElMessage = () => {
  ElMessage({
    message: "修改成功",
    type: "success",
  });
};
/**
 *
 * 白名单详情弹出框
 *
 * ***/
// 弹出框控制器
const whitelistDialog = ref(false);
// 弹出框标题
const whitelistDialogTitle = ref("");
// 弹出框传入data
const whitelistRowData = ref();
/**
 *
 * 树形目录组件
 *
 * ***/
// 树形组件
const whitelistDirRef = ref();
// 树形组件pinia注册
const treeStore = useTreeStore();
const userStore = useUserStore();
// 白名单表格
const whitelistTable = ref();
// 白名单表格数据
const whitelistTableData = ref([]);
// 表格选中复选框时 展示或隐藏删除按钮的标识
let handleSelectionChangeFlag = ref(true);
// 表格的total
let whitelistTotal = ref(0);
// 表格新增按钮标识
let whitelistAddFlag = ref(true);
// 模态框v-model
const dialogFormVisible = ref();
// 新增的模态框form表单ref
const whitelistForm = ref();
// true为文件夹，false为文件
const dirFlag = ref(true);
// 树形组件导出是否可以导出根目录
const rootDirFlag = ref(false);
// 选中的行的数据
const selectionChangeValue = ref(null);
const rules = reactive({
  policyName: [{ required: true, message: "路径不能为空", trigger: "blur" }],
});
let form = reactive({
  policyName: "",
});
const queryWhitelistForm = async () => {
  if (!whitelistForm) return;
  await whitelistForm.value.validate((valid, fields) => {
    if (valid) {
      if (!treeStore.treeDeviceId) {
        return;
      }
      let params = [];
      whitelistTableData.value.map((item) => {
        item.path;
        params.push(item);
      });
      params.push({
        path: form.policyName,
      });
      req_KillEdit(treeStore.treeDeviceId, params).then(
        (res) => {
          successElMessage();
          form.policyName = "";
          whitelistTable.value.getTableData();
        },
        (err) => {
          ElMessage.error(err);
        }
      );
      dialogFormVisible.value = false;
    }
  });
};

const killSync = async () => {
  req_SyncAdd(treeStore.treeDeviceId).then(
    (res) => {
      successElMessage();
      form.policyName = "";
      whitelistTable.value.getTableData();
    },
    (err) => {
      ElMessage.error(err);
    }
  );
  dialogFormVisible.value = false;
};

// 修改名称事件
const editNameFn = async (row) => {
  if (!treeStore.treeDeviceId) {
    return;
  }
  let params = {
    deviceId: treeStore.treeDeviceId,
    policyName: row.policyName,
  };
  let body = {
    policyId: row.policyId,
  };
  await req_setWhitelistPolicylist(params, body).then(
    (res) => {
      if (res.data.succeed) {
        successElMessage();
      }
    },
    (err) => {
      ElMessage.error(err);
    }
  );
  whitelistTable.value.getTableData();
};
const arrangeFn = async (row) => {
  if (!treeStore.treeDeviceId) {
    return;
  }
  let deployParam = {
    deviceId: treeStore.treeDeviceId,
    policyId: row.policyId,
  };
  if (row.status === true) {
    await req_setWhitelistDeploy(deployParam).then(
      (res) => {
        successElMessage();
      },
      (err) => {
        ElMessage.error(err);
      }
    );
  } else {
    await req_setWhitelistUndeploy(deployParam).then(
      (res) => {
        successElMessage();
      },
      (err) => {
        ElMessage.error(err);
      }
    );
  }
  whitelistTable.value.getTableData();
};
// 白名单列表日志表格 列名与数据源设置
const whitelistTableFields = reactive([{ name: "path", label: "路径" }]);

const handleSelectionChange = (val) => {
  selectionChangeValue.value = val;
  rootDirFlag.value = true;
  if (val.length >= 1) {
    handleSelectionChangeFlag.value = false;
  } else {
    handleSelectionChangeFlag.value = true;
  }
};
const handleAddWhitelist = () => {
  dialogFormVisible.value = true;
};
const downloadWhitelist = () => {
  treeStore.directoryDialogVModel = true;
  dirFlag.value = true;
};
const uploadWhitelist = () => {
  treeStore.directoryDialogVModel = true;
  dirFlag.value = false;
};
// { name: '修改', ev: handleUpdateSyslog, icon: Edit, disabled: handleSelectionChangeEditFlag },
const headerOperation = [
  { name: "新增", ev: handleAddWhitelist, icon: Plus, disabled: whitelistAddFlag },
  // {name: '下发', ev: killSync, icon: Upload, disabled: whitelistAddFlag, type: 'file'},
];
const emit = defineEmits(["toCurrentWitelist"]);
const detailsFn = (index, row) => {
  dirFlag.value = false;
  if (row.status == 1) {
    emit("toCurrentWitelist", index, row);
  } else {
    whitelistDialog.value = true;
    whitelistDialogTitle.value = row.policyName;
    whitelistRowData.value = row;
    selectionChangeValue.value = row;
  }
};
const delWhitelist = async (index, row) => {
  if (!treeStore.treeDeviceId) {
    return;
  }
  let deleteWhitelistParams = whitelistTableData.value.filter(
    (item) => item.path !== row.path
  );

  await req_KillEdit(treeStore.treeDeviceId, deleteWhitelistParams).then(
    (res) => {
      successElMessage();
    },
    (err) => {
      ElMessage.error(err);
    }
  );
  whitelistTable.value.getTableData();
};
const operationCol = [{ name: "删除", ev: delWhitelist, popconfirm: true }];
const getWhitelistTableData = async (countParams, searchParams) => {
  if (treeStore.treeDeviceId) {
    whitelistAddFlag.value = false;
    let whitelistParams = {
      page: searchParams.$page,
      size: searchParams.$limit,
    };
    await req_KillList(treeStore.treeDeviceId, whitelistParams).then(
      (res) => {
        if (res.data.list) {
          whitelistTableData.value = res.data.list;
          whitelistTotal.value = res.data.list.length;
        }
      },
      (err) => {
        whitelistTable.value.finish();
      }
    );
  } else {
    whitelistTableData.value = [];
  }
  whitelistTable.value.finish();
  treeStore.treeLinkedTableRef = whitelistTable;
};

const handleDialogButton = async (ref, path) => {
  let paramsPath = path;
  let importParams = {
    file: paramsPath
      .split(/\\/g)
      .filter((item) => item !== "")
      .join("\\\\"),
  };
  treeStore.directoryDialogVModel = false;
  console.log(path);
  // dirFlag 为true是导出，false是导入
  if (dirFlag.value === false) {
    await req_importWhitelist(treeStore.treeDeviceId, importParams).then(
      (res) => {
        if (res.data.succeed) {
          successElMessage();
          whitelistTable.value.getTableData();
        } else {
          ElMessage.error("文件错误");
        }
      },
      (err) => {
        ElMessage.error(err);
      }
    );
  } else {
    let thisPolicyIds = [];
    selectionChangeValue.value.map((item) => {
      thisPolicyIds.push(item.policyId);
    });

    let exportParams = {
      file:
        paramsPath
          .split(/\\/g)
          .filter((item) => item !== "")
          .join("\\\\") +
        "\\\\" +
        selectionChangeValue.value[0].policyName +
        Math.floor(new Date().getTime() / 1000) +
        ".csv",
      // file: paramsPath.split(/\\/g).filter( item => item !== '' ).join('\\\\') +'.csv',
      policyIds: thisPolicyIds,
    };
    await req_exportWhitelist(treeStore.treeDeviceId, exportParams).then(
      (res) => {
        if (res.data.succeed) {
          successElMessage();
        } else {
          ElMessage.error("文件错误");
        }
      },
      (err) => {
        ElMessage.error(err);
      }
    );
  }
  rootDirFlag.value = false;
};
</script>

<style lang="scss" scoped></style>
